#!/usr/bin/env python3
import sys
import os

def remove_embedded_html(input_file, output_file=None):
    if output_file is None:
        base, ext = os.path.splitext(input_file)
        output_file = f"{base}.fix{ext}"

    with open(input_file, "r", encoding="utf-8") as infile, open(output_file, "w", encoding="utf-8") as outfile:
        buffer = ""
        remove_start = -1
        while (chunk := infile.read(1)):  # Read one character at a time
            if remove_start >= 0:
                if chunk == '\\':
                    remove_start += 1
                    # remove escaped single characters
                    chunk = infile.read(1) # should be readble, should be "
                elif chunk == '"':
                    # print(f"removal end: {remove_start}")
                    chunk = infile.read(1)
                    # if chunk == ',':
                    #     print(f"next char is:, ;remove")
                    # else:
                    #     print(f"next chat is:{chunk} ;keep")
                    #     buffer += chunk
                    remove_start = -1
                else:
                    remove_start += 1
                continue
            buffer += chunk
            pattern_1 = "\"brief\":\""          # "brief":"<p>....</p>", others.. # won't macth: ,"brief": null, ...
            pattern_2 = "\"schedule\":\""
            # Check if the last part of the buffer matches "brief"
            if buffer.endswith(pattern_1):
                # remove following text until encoutering a " without preceeding \
                matchedlen = len(pattern_1)
                buffer = buffer[:-matchedlen]  # Remove the "brief" substring
                remove_start = 0
                # print(f"hit: {pattern_1}")
            elif buffer.endswith(pattern_2):
                matchedlen = len(pattern_2)
                buffer = buffer[:-matchedlen]  # Remove the "brief" substring
                remove_start = 0
                # print(f"hit: {pattern_2}")
            maxmacthedlen = max(len(pattern_1), len(pattern_2))
            if len(buffer) > maxmacthedlen:  # Write the first character(s) to avoid delays
                outfile.write(buffer[:-maxmacthedlen])
                buffer = buffer[-maxmacthedlen:]

        # Write any remaining characters in the buffer
        outfile.write(buffer)
        outfile.flush()

if __name__ == "__main__":
    # Ensure at least one argument (input file) is provided
    if len(sys.argv) < 2:
        print("Usage: python script.py <input_file> [output_file]")
        sys.exit(1)

    # Get the input and output file names
    input_file = sys.argv[1]
    output_file = sys.argv[2] if len(sys.argv) > 2 else None

    # Call the function to process the file
    remove_embedded_html(input_file, output_file)
